package com.example.automatic.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.telephony.SmsMessage;

import com.example.automatic.single.GlobalHandler;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SMSBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        //短信监听
        if ("android.provider.Telephony.SMS_RECEIVED".equals(intent.getAction())) {
            Bundle bundle = intent.getExtras();
            if (bundle == null) {
                return;
            }
            Object[] objects = (Object[]) bundle.get("pdus");
            if (objects == null) {
                return;
            }
            for (Object pdus : objects) {

                String format = intent.getStringExtra("format");
                byte[] pdusByte = (byte[]) pdus;

                SmsMessage sms = SmsMessage.createFromPdu(pdusByte, format);

                smsAnalysis(sms);
            }
        }
    }

    private void smsAnalysis(SmsMessage sms) {

        //接收短信的号码
        String smsMobile = sms.getOriginatingAddress();
        //短信内容
        String smsContent = sms.getMessageBody();

        if (smsMobile == null || smsContent == null) {
            return;
        }
        // 正则表达式截取短信中的6位验证码
        String regEx = "(?<![0-9])([0-9]{6})(?![0-9])";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(smsContent);
        // 如果找到通过Handler发送给主线程
        String code = null;
        while (matcher.find()) {
            code = matcher.group();
        }
        if (code == null) {
            return;
        }
        GlobalHandler handler = GlobalHandler.getInstance();
        Message message = null;
        if (smsMobile.equals("95533")) {
            message = new Message();
            message.what = 95533;
            message.obj = code;
        }
        if (message == null) {
            return;
        }
        handler.sendMessageDelayed(message, 1500);

    }
}
